package id.co.shuba.spamobile;

import id.co.shuba.spamobile.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Encryptor {	
	public static final String ENC_DES = "DESede/CBC/PKCS5Padding";
	//public static final String ENC_AES = "AES/CBC/PKCS5Padding";
	public static final String ENC_AES = "AES/CBC/PKCS5Padding";
	
	public static final String ALGO_DES = "DESede";
	public static final String ALGO_AES = "AES";	
	
	private String enc;
	private String algorithm;
	private String key;
	private String initializationVector;
	
	public Encryptor(String enc, String algorithm, String key, String initializationVector) {
		this.key = key;
		this.initializationVector = initializationVector;
		this.enc = enc;
		this.algorithm = algorithm;
	}

	public String encryptText(String plainText) throws Exception {		
		byte[] plaintext = plainText.getBytes();
		byte[] keyData = key.getBytes();	

		Cipher cipher = Cipher.getInstance(enc);
		SecretKeySpec myKey = new SecretKeySpec(keyData, algorithm);
		IvParameterSpec ivspec = new IvParameterSpec(
				initializationVector.getBytes());

		cipher.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
		byte[] cipherText = cipher.doFinal(plaintext);

		return Base64.encodeBytes(cipherText);
	}

	public String decryptText(String cipherText) throws Exception {
		byte[] encData = Base64.decode(cipherText);
		Cipher decipher = Cipher.getInstance(enc);
		byte[] keyData = key.getBytes();
		SecretKeySpec myKey = new SecretKeySpec(keyData, algorithm);
		IvParameterSpec ivspec = new IvParameterSpec(
				initializationVector.getBytes());
		decipher.init(Cipher.DECRYPT_MODE, myKey, ivspec);
		byte[] plainText = decipher.doFinal(encData);
		return new String(plainText);
	}
}
